package com.example.lovewordsapplication.utils;

import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

/**
 * 键盘工具类
 *
 * @author Leung
 * @date 2020/4/6 22:55
 */
public class KeyboardUtil {

    /**
     * 显示软键盘
     *
     * @param view 要获取焦点并显示软键盘的view
     */
    public static void showKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            view.requestFocus();
            imm.showSoftInput(view, 0);
        }
    }

    /**
     * 隐藏软键盘
     *
     * @param view 需要清除焦点的view(也可以是其他ViewTree)
     */
    public static void hideKeyboard(View view){
        InputMethodManager imm = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            view.clearFocus();
            imm.hideSoftInputFromWindow(view.getWindowToken(),0);
        }
    }

    /**
     * 切换软键盘显示或者隐藏状态
     *
     * @param view 随意一个ViewTree即可，主要是获取windowToken()
     */
    public static void  toggleSoftInput(View view){
        InputMethodManager imm = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.toggleSoftInput(0,0);
        }
    }

}
